package com.bitejiuyeke.job_publish.controller;

import com.bitejiuyeke.job_publish.common.AppResult;
import com.bitejiuyeke.job_publish.common.PageResult;
import com.bitejiuyeke.job_publish.common.ResultCode;
import com.bitejiuyeke.job_publish.config.AppConfig;
import com.bitejiuyeke.job_publish.config.RabbitMQConfig;
import com.bitejiuyeke.job_publish.controller.params.SendRecordModifyStateDTO;
import com.bitejiuyeke.job_publish.controller.params.SendRecordPageByJobDTO;
import com.bitejiuyeke.job_publish.controller.params.SendRecordPageByReceiveUserDTO;
import com.bitejiuyeke.job_publish.controller.params.SendRecordPageByUserDTO;
import com.bitejiuyeke.job_publish.enums.SendRecordStateEnum;
import com.bitejiuyeke.job_publish.model.Job;
import com.bitejiuyeke.job_publish.model.Offer;
import com.bitejiuyeke.job_publish.model.SendRecord;
import com.bitejiuyeke.job_publish.model.User;
import com.bitejiuyeke.job_publish.mq.model.OfferedMQ;
import com.bitejiuyeke.job_publish.service.IOfferService;
import com.bitejiuyeke.job_publish.service.ISendRecordService;
import com.bitejiuyeke.job_publish.utils.StringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.PositiveOrZero;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Author 比特就业课
 */
// API描述
@Tag(name = "投递操作相关接口")
// 日志
@Slf4j
// 校验
@Validated
// Controller注解，返回的对象用JSON形式表示
@RestController
// 路径映射
@RequestMapping("/deliver")
public class SendRecordController {

    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private ISendRecordService service;
    @Resource
    private IOfferService offerService;

    @Operation(summary = "用户投递职位")
    @Parameter(name = "jobId", description = "职位Id", in = ParameterIn.QUERY)
    @PostMapping("/add")
    public AppResult add (HttpServletRequest request,
                          @PositiveOrZero(message = "职位编号不正确") @RequestParam("jobId") Long jobId) {
        // 获取当前用户Id
        Long userId = (Long) request.getAttribute(AppConfig.TOKEN_USER_ID);
        // 投递对象
        SendRecord record = new SendRecord();
        record.setUserId(userId);
        record.setJobId(jobId);
        // 调用Service
        service.create(record);
        return AppResult.success();
    }

    @Operation(summary = "获取投递记录详情")
    @GetMapping("/details/{id}")
    public AppResult<SendRecord> selectById (HttpServletRequest request,
                                      @PositiveOrZero(message = "请输入投递记录Id") @PathVariable("id") Long id) {
        // 获取当前用户Id
        Long userId = (Long) request.getAttribute(AppConfig.TOKEN_USER_ID);
        SendRecord sendRecord = service.selectById(id);
        if (sendRecord == null) {
            return AppResult.failed("没有找到对应的记录");
        }
        // 校验是否为自己的投递记录
        if (sendRecord.getUserId() != userId && sendRecord.getReceiveUserId() != userId) {
            return AppResult.failed(ResultCode.FAILED_NOT_PERMISSION);
        }
        // 如果是第一次查看，设置为已读
        if (SendRecordStateEnum.valueOf(sendRecord.getState()) == SendRecordStateEnum.POSTED) {
            sendRecord.setState((byte) SendRecordStateEnum.READ.getCode());
            service.modifyState(sendRecord);
        }
        return AppResult.success(sendRecord);
    }

    @Operation(summary = "更新投递状态")
    @PostMapping("/state")
    @Transactional
    public AppResult modifyState (HttpServletRequest request,
                                  @Validated @RequestBody SendRecordModifyStateDTO param) {
        // 获取用户Id
        Long userId = (Long) request.getAttribute(AppConfig.TOKEN_USER_ID);
        // 状态
        SendRecordStateEnum stateEnum = SendRecordStateEnum.valueOf(param.getState());
        // 转换对象
        SendRecord update = new SendRecord();
        update.setId(param.getId());
        update.setReceiveUserId(userId);
        update.setState(param.getState());
        update.setRemark(param.getRemark());
        // 修改状态
        service.modifyState(update);
        // 发Offer
        SendRecord sendRecord = service.selectById(param.getId());
        if (stateEnum == SendRecordStateEnum.OFFERED) {
            Offer offer = new Offer();
            offer.setJobId(sendRecord.getJobId());
            offer.setUserId(sendRecord.getUserId());
            offer.setSendRecordId(sendRecord.getId());
            offerService.create(offer);
            log.info("发Offer成功.");
        }
        // 获取投递用户信息

        User sendUser = sendRecord.getSendUser();
        // 消息队列-发送邮件
        if (!StringUtils.isEmpty(sendUser.getEmail())) {
            // 获取职位信息
            Job job = sendRecord.getJob();
            // 消息队列-发送邮件
            OfferedMQ offeredMQ = new OfferedMQ();
            offeredMQ.setTargetNum(sendUser.getEmail());
            offeredMQ.setStateEnum(stateEnum);
            String content = "您投递的职位: " + job.getTitle() + ", 邀约状态已更新为: "
                    + SendRecordStateEnum.valueOf(sendRecord.getState()).getMessage() + ". " +
                    "请登录比特校园兼职系统查看详情.";
            offeredMQ.setContent(content);
            // 发送消息
            rabbitTemplate.convertAndSend(RabbitMQConfig.BITE_JOB_EXCHANGE_NAME,
                    RabbitMQConfig.BITE_JOB_OFFERED_ROUTING_KEY, offeredMQ);
        }

        return AppResult.success();
    }

    @Operation(summary = "根据接收者信息查询投递记录")
    @GetMapping("/pageByReceiveUser")
    public AppResult selectPageByReceiveUser (HttpServletRequest request,
                                       @Validated SendRecordPageByReceiveUserDTO param) {
        // 获取当前用户
        Long userId = (Long) request.getAttribute(AppConfig.TOKEN_USER_ID);
        param.setReceiveUserId(userId);
        // 条件对象
        SendRecord sendRecord = new SendRecord();
        BeanUtils.copyProperties(param, sendRecord);
        // 查询结果
        PageResult<SendRecord> pageResult = service.selectPageByReceiveUser(sendRecord);
        // 返回
        return AppResult.success(pageResult);
    }

    @Operation(summary = "根据用户信息查询投递记录")
    @GetMapping("/pageByUser")
    public AppResult selectPageByUser (HttpServletRequest request,
                                       @Validated SendRecordPageByUserDTO param) {
        // 获取当前用户
        Long userId = (Long) request.getAttribute(AppConfig.TOKEN_USER_ID);
        param.setUserId(userId);
        // 条件对象
        SendRecord sendRecord = new SendRecord();
        BeanUtils.copyProperties(param, sendRecord);
        // 查询结果
        PageResult<SendRecord> pageResult = service.selectPageByUser(sendRecord);
        // 返回
        return AppResult.success(pageResult);
    }

    @Operation(summary = "根据职位信息查询投递记录")
    @GetMapping("/pageByJob")
    public AppResult selectPageByJob (HttpServletRequest request,
                                       @Validated SendRecordPageByJobDTO param) {
        // 获取当前用户
        Long userId = (Long) request.getAttribute(AppConfig.TOKEN_USER_ID);
        // 条件对象
        SendRecord sendRecord = new SendRecord();
        BeanUtils.copyProperties(param, sendRecord);
        // 查询结果
        PageResult<SendRecord> pageResult = service.selectPageByJob(sendRecord);
        // 返回
        return AppResult.success(pageResult);
    }
}
